﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace PTViewer
{
    public partial class ForumsListForm : Form
    {
        public ForumsListForm()
        {
            InitializeComponent();
            InitializeTreeView();
        }
        private void InitializeTreeView()
        {
            var fpath = "f.html";
            string html = "";

            var url = Helper.FORUMS_LIST_URL;
            
            bool needDown = false;

            if (!File.Exists(fpath) || needDown)
            {
                html = new Helper().DownloadWebPage(url);
                File.WriteAllText(fpath, html, Encoding.UTF8);
            }
            else
            {
                html = File.ReadAllText(fpath);
            }

            FillTree(html);

        
        }
      

        private void FillTree(string html)
        {
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);

            var tr_ = doc.DocumentNode
                .SelectSingleNode("//table[@class='forumTable']")
                .SelectNodes("tr");

            treeView1.BeginUpdate();

            int i = -1;
            foreach (var tr in tr_.Skip(1))
            {

                if (tr.ChildNodes.Count == 3)
                {
                    //var msg = tr.ChildNodes[3].ChildNodes[0];
                    var tt = tr.SelectSingleNode("td").InnerText;
                    treeView1.Nodes.Add(tt);
                    i++;
                }
                else
                {
                    var msg = tr.ChildNodes[3].SelectSingleNode("a").InnerText;
                    treeView1.Nodes[i].Nodes.Add(msg);
                   
                }
            }
           
            treeView1.EndUpdate();
        }
    }
}
